﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace RENIT.DragNDropUpload.Utils
{
    public class DocumentLibraryAdapter
    {
        private WebGuard webGuard;
        private SPFolder folder;
        public string TargetFolderUrl { get; private set; }
        private SPDocumentLibrary library;
        public DocumentLibraryAdapter(WebGuard guard, string webRelativeFolderUrl)
        {
            webGuard = guard;
            TargetFolderUrl = webRelativeFolderUrl;
            folder = webGuard.GetFolder(webRelativeFolderUrl);
            library = webGuard.GetList(folder.ParentListId) as SPDocumentLibrary;
            if (library == null)
            {
                throw new Exception("Specified folder is not in a document library");
            }
        }

        public DocumentLibraryAdapter(WebGuard guard, Guid id)
        {
            webGuard = guard;
            library = webGuard.GetList(id) as SPDocumentLibrary;
            if (library == null)
            {
                throw new Exception("Specified folder is not in a document library");
            }
            folder = library.RootFolder;
            TargetFolderUrl = folder.Url;
        }

        public bool SaveFile(string fileName, System.IO.Stream stream, bool overwrite)
        {
            using (webGuard.AllowUsafeUpdates())
            {
                foreach (SPFile file in folder.Files)
                {
                    if (file.Name.Equals(fileName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (overwrite)
                        {
                            UpdateFileStream(file, stream);
                            return true;
                        }
                        else
                            return false;
                    }
                }
                folder.Files.Add(fileName, stream);
                return true;
            }
        }

        private void UpdateFileStream(SPFile file, System.IO.Stream stream)
        {
            if (library.ForceCheckout)
            {
                file.CheckOut();
            }
            file.SaveBinary(stream);
            if (library.ForceCheckout)
            {
                file.CheckIn("Uploaded by drag&drop", SPCheckinType.MajorCheckIn);
            }
            if (file.Level != SPFileLevel.Published)
            {
                file.Publish("Uploaded by drag&drop ant published then automatically");
            }
        }
    }
}
